package com.market.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.StpUtil;
import com.market.entity.UserAddress;
import com.market.service.UserAddressService;
import com.market.constants.ResultCode;
import com.market.exception.ServiceException;
import com.market.model.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * 用户地址控制器
 * 处理用户收货地址相关的功能，包括添加地址、删除地址和获取地址列表
 * 所有接口需要用户登录才能访问
 */
@RestController
@RequestMapping("/user/address")
@SaCheckLogin
public class UserAddressController {
  @Autowired
  private UserAddressService userAddressService;
  
  /**
   * 创建用户收货地址
   * 将当前登录用户ID与地址信息关联保存
   * @param address 包含地址信息的实体对象
   * @return 操作结果
   */
  @PostMapping
  public R create(@RequestBody UserAddress address){
    UserAddress userAddress = new UserAddress();
    userAddress.setUserId(StpUtil.getLoginIdAsString());
    userAddress.setAddress(address.getAddress());
    userAddress.setPhone(address.getPhone());
    userAddress.setName(address.getName());
    userAddress.setCreateTime(new Date().getTime());
    userAddress.setUpdateTime(new Date().getTime());
    boolean save = userAddressService.save(userAddress);
    if (!save) throw new ServiceException(ResultCode.SaveError);
    return R.ok();
  }
  
  /**
   * 删除用户收货地址
   * 验证地址所属用户是否为当前登录用户，防止越权操作
   * @param id 地址ID
   * @return 操作结果
   */
  @DeleteMapping("/{id}")
  public R delete(@PathVariable String id) {
    UserAddress userAddress = userAddressService.getById(id);
    if (null == userAddress) throw new ServiceException(ResultCode.NotFindError);
    if (!userAddress.getUserId().equals(StpUtil.getLoginIdAsString())) throw new ServiceException(ResultCode.NotFindError);
    boolean remove = userAddressService.removeById(id);
    if (!remove) throw new ServiceException(ResultCode.DeleteError);
    return R.ok();
  }
  
  /**
   * 获取当前用户的收货地址列表
   * @return 返回用户所有收货地址
   */
  @GetMapping("/list")
  public R<List> list() {
    String userId = StpUtil.getLoginIdAsString();
    List<UserAddress> list = userAddressService.lambdaQuery().eq(UserAddress::getUserId, userId).list();
    return R.ok(list);
  }
}
